package com.shy.task.job;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.shy.collect.entity.UserInfo;
import com.shy.collect.mapper.TradeOrderMapper;
import com.shy.collect.mapper.UserInfoMapper;
import com.shy.configs.common.mail.MailClient;
import com.shy.configs.common.mail.model.AttachFile;
import com.shy.configs.common.mail.model.MailProperties;
import com.shy.configs.mapping.TradeDayBill;
import com.shy.task.job.excel.DayBillHeader;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Component
public class TaskJob {

    @Value("${bill.path}")
    private String billPath;

    @Value("${spring.mail.username}")
    private String mailFrom;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private TradeOrderMapper tradeOrderMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private MailClient mailClient;

    //生成日对账单， 一个用户一天一个对账单，excel文件
    @XxlJob("dftDayBill")
    public void makeDayBill() {
        //1.查询昨天有成功支付记录的 商户号
        Date current = new Date();
        DateTime yesterday = DateUtil.offsetDay(current, -1);

        //保留到年-月-日部分
        DateTime beginDate = DateUtil.truncate(yesterday, DateField.DAY_OF_MONTH);
        DateTime endDate = DateUtil.truncate(current, DateField.DAY_OF_MONTH);

        List<String> userNoList = tradeOrderMapper.selectUserNoList(beginDate, endDate);

        String dateText = new SimpleDateFormat("yyyyMMdd").format(yesterday);
        //创建日期目录 java.nio中的类
        try {
            Path path = Paths.get(billPath, dateText);
            if (!Files.exists(path)) {
                //创建目录
                Files.createDirectories(path);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        //2.每个用户生成excel文件
        for (String userNo : userNoList) {
            threadPoolExecutor.execute(() -> {
                //查询用户的账单
                List<TradeDayBill> tradeOrderList = tradeOrderMapper.selectBillByUserNo(userNo, beginDate, endDate);
                //生成excel文件 81739922425681879042-20240108-bill.xlsx
                String fileName = userNo + "-" + dateText + "-bill.xlsx";

                File file = Paths.get(billPath, dateText, fileName).toFile();
                //写excel文件
                EasyExcel.write(file, DayBillHeader.class)
                        .sheet("网关日对账单文件")
                        .doWrite(tradeOrderList);
            });

        }
    }


    //对账单邮件
    @XxlJob("sendDayBillMail")
    public void sendFileEmail() {
        Date current = new Date();
        DateTime yesterday = DateUtil.offsetDay(current, -1);

        //保留到年-月-日部分
        // 将昨天的日期截断到天的开始，即昨天的0点
        DateTime beginDate = DateUtil.truncate(yesterday, DateField.DAY_OF_MONTH);
        // 将当前日期截断到天的开始，即今天0点
        DateTime endDate = DateUtil.truncate(current, DateField.DAY_OF_MONTH);

        // 查询在指定日期范围内的所有用户信息
        List<UserInfo> userInfos = userInfoMapper.selectUserEmail(beginDate, endDate);

        // 格式化昨天的日期为"yyyy-MM-dd"格式，用于显示或处理
        String dateText = new SimpleDateFormat("yyyy-MM-dd").format(yesterday);
        // 格式化昨天的日期为"yyyyMMdd"格式，通常用于创建文件夹名
        String folderName = new SimpleDateFormat("yyyyMMdd").format(yesterday);
        String fileName = "";
        boolean send = false;
        for (UserInfo userInfo : userInfos) {
            // 发送邮件
            MailProperties prop = new MailProperties();
            prop.setFrom(mailFrom);
            prop.setTo(new String[]{userInfo.getUserEmail()});
            prop.setSubject(dateText + "日对账单");
            prop.setText("商家每日对账单，参看附件");

            fileName = userInfo.getUserNo() + "-" + folderName + "-bill.xlsx";

            Path path = Paths.get(billPath , folderName, fileName);
            System.out.println("----"+path+"------");

            if (Files.exists(path)) {
                // 创建一个AttachFile对象用于封装附件信息
                AttachFile attachFile = new AttachFile();

                // 设置附件的名称为日期文本后缀为“日对账单”，便于识别对账单所属日期
                attachFile.setName(dateText + "日对账单");

                // 设置附件的文件路径，将Path对象转换为File对象，以便AttachFile对象使用
                attachFile.setFile(path.toFile());

                // 设置prop对象的附件列表，此处仅包含一个附件，使用List.of创建不可变列表
                prop.setAttachFiles(List.of(attachFile));
            }

            send = mailClient.sendAttachmentsMail(prop);
            System.out.println("发送邮件的日志：" + userInfo.getUserNo() + "|" + userInfo.getUserEmail() + "|" + send);

        }
    }
}
